package com.txc.cloud.auth.common.security;

import cn.hutool.core.util.StrUtil;
import com.txc.common.global.result.Result;
import com.txc.common.utils.jwt.TokenManager;
import com.txc.common.utils.middleware.RedisUtils;
import com.txc.common.utils.supply.HttpServletResponseUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.txc.common.global.constant.StrConstant.AUTHORIZATION;

/**
 * 注销处理器
 *
 * @ClassName: AuthLogoutHandler
 * @Author: TXC
 * @Date: 2022-07-30 16:28
 **/
@Component
public class AuthLogoutHandler implements LogoutHandler {
    @Resource
    public RedisUtils redisUtils;
    @Resource
    public TokenManager tokenManager;

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        String token = request.getHeader(AUTHORIZATION);
        if (StrUtil.isNotBlank(token)) {
            String userId = tokenManager.getUserId(token);
            redisUtils.delete(tokenManager.getCacheKey() + userId);
        }
        HttpServletResponseUtil.out(response, Result.ok());
    }
}
